import time
from CheckTextWidget import CheckTextWidget
import tkinter as tk
from tkinter import messagebox


class ctwdata():
    def __init__(self, check_var, text):
        self.check_var = check_var
        self.text = text


class CheckTextWidgets(tk.Frame):
    def set_check(self, index, check_var):
        self.widget_stact[index].set_check(check_var)

    def set_check_all(self,  check_var):
        for i in range(len(self.widget_stact)):
            self.widget_stact[i].set_check(check_var)

    def get_check_text(self):
        ret = {}
        for i in range(len(self.widget_stact)):
            ret[i] = ctwdata(self.widget_stact[i].get_clicked(
            ), self.widget_stact[i].get_txt())
        return ret

    def get_check_text_for_index(self, index):
        return ctwdata(self.widget_stact[index].get_clicked(
        ), self.widget_stact[index].get_txt())

    def add_widgets(self, check_var=False, text=""):
        self.widget_stact.append(CheckTextWidget(self,
                                                 check_var=check_var,
                                                 text=text,
                                                 width=self.width))
        self.widget_stact[-1].pack()

    def sub_widgets(self):
        if len(self.widget_stact) == 1:
            messagebox.showinfo("提示", "最后一个控件无法删除")
            return
        self.widget_stact[-1].destroy()
        self.widget_stact.pop()

    def sub_widgets_for_index(self, index):
        if index < 0 or index >= len(self.widget_stact):
            messagebox.showinfo("提示", "超出范围")
            return
        if len(self.widget_stact) == 1:
            messagebox.showinfo("提示", "最后一个控件无法删除")
            return
        self.widget_stact[index].destroy()
        del self.widget_stact[index]

    def __init__(self, master, check_var=False, text="", width=30):
        super().__init__(master)
        self.width = width
        self.widget_stact = []
        self.add_widgets(check_var, text)


if __name__ == '__main__':
    root = tk.Tk()
    root.title("CheckTextWidgets")
    root.geometry("400x300")

    def on_click_add():
        ctw.add_widgets(True, time.strftime("%Y-%m-%d %H:%M:%S"))
        a = ctw.get_check_text()
        for i in a:
            print(i, a[i].check_var, a[i].text)
        print("-"*10)

    def on_click_sub():
        ctw.sub_widgets()

    def on_click_sub_index():
        ctw.sub_widgets_for_index(0)
    f = tk.Frame(root)
    f.pack(side="left", fill="y")
    f.config(bg="red")
    btn1 = tk.Button(root, text="加一个控件", command=on_click_add)
    btn1.pack()
    btn2 = tk.Button(root, text="删除最后一个", command=on_click_sub)
    btn2.pack()

    btn3 = tk.Button(root, text="指定序号删除0", command=on_click_sub_index)
    btn3.pack()

    ctw = CheckTextWidgets(f, False, time.strftime("%Y-%m-%d %H:%M:%S"), 20)
    ctw.pack()
    root.mainloop()
